const crypto = require('crypto');
const jwt = require('jsonwebtoken');

const total_config = require("../config.js");

const default_jwtKey = 'RgVRWFBHdafagfsgswreasdkp9epV'
const jwtKey = total_config.key || default_jwtKey;

function sha256(input) {
    return crypto.createHash('sha256').update(input).digest('hex');
}

async function verifyJwtToken(token) {
    // 异步转同步 强制立即执行jwt的解码操作
    return new Promise((resolve, reject) => {
        jwt.verify(token, jwtKey, (err, decoded) => {
            if (err) {
                resolve({ success: true, msg: "卡密错误，验证卡密失败" });
            } else if (parseInt(+new Date() / 1000) >= decoded.exp) {
                resolve({ success: true, msg: "卡密已过期，验证卡密失败" });
            } else {
                resolve({ success: true, msg: "验证成功", data: decoded });
            }
        });
    });
}

/*
 * 提供用户登录状态的非敏感数据
 * 提供过期时间: exp = {expiresIn: '168h'}
 */
async function createUserJwtToken(data, exp) {
    let token = jwt.sign(data, jwtKey, exp);
    return token;
}

module.exports = {jwt, jwtKey, sha256, verifyJwtToken, createUserJwtToken};
